<?php

namespace app\common\service;

use app\common\service\traits\InstanceTrait;
use app\model\site\User;
use app\model\store\DistRewardLog;
use app\model\store\Order;
use app\model\store\OrderRefund;
use app\model\store\OrderRefundItem;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\db\Query;
use think\facade\Db;

class CommonDistService
{

    use InstanceTrait;

    /** 团队查询
     * @param int $userId
     * @param string $levelType
     * @return Query
     */
    public function teamQuery(int $userId, string $levelType=''): Query
    {
        $levelWhere = "2,3";    // 默认向下查询两级
        if ($levelType == 'one'){
            $levelWhere = "2";
        }elseif ($levelType == 'two'){
            $levelWhere = "3";
        }

        return Db::table(" (
	SELECT
		@ids AS _ids,
		@l:=@l+1 AS level,
		(SELECT @ids := GROUP_CONCAT( id ) FROM `user` WHERE FIND_IN_SET( parent_id, @ids )) cids 
	FROM
		`user`,
		( SELECT @ids:=$userId , @l:=0) pid 
	) AS scope,
	`user`  ")
            ->whereRaw(" scope._ids IS NOT NULL AND FIND_IN_SET( `user`.id, scope._ids ) AND FIND_IN_SET(level, '$levelWhere') AND user.id<>$userId ");
    }

    /**
     * 订单返佣
     * @param Order $order
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function giveRewardByOrder(Order $order){
        // 如果
        $siteId = $order->site_id;
        $config = CommonSiteConfigService::instance()->getConfigValue($siteId, CommonSiteConfigService::DIST);
        if ($config['is_on']==0){   // 未开启分销，不返利
            return;
        }
        if ($config['one_reward_rate']<=0){ // 一级返利金额为0，不返利
            return;
        }

        $user = User::find($order->user_id);
        if (!$user){    // 用户不存在，不返利
            return;
        }
        // 直属上级
        $oneParent = User::with('storeManager')->find($user->parent_id);
        if (!$oneParent){   // 直属上级不存在，不返利
            return;
        }
        if ($config['is_on_store_manager']==1 && !$oneParent->storeManager){ // 开启了店长功能，但上级不是店长，不返利
            return;
        }

        // 查询当前订单对应的已经退款的订单商品ids[]
        $orderItemIds = OrderRefundItem::field('orei.*,ore.refund_status refund_status')->alias('orei')
            ->join('order_refund ore','ore.id = orei.order_refund_id')
            ->where('orei.order_id', $order->id)
            ->where('ore.refund_status', 1)
            ->column('order_item_id');
        $amount = 0;    // 当前订单中能够参与分销的总金额
        foreach ($order->items as $item){
            // 是分销商品 && 没有退款
            if ($item['is_dist'] && !in_array($item['id'], $orderItemIds)){
                $amount += $item['total_price'];  // 累加付款金额
            }
        }

        $firstAmount = round($amount * ($config['one_reward_rate']/100), 2);
//        $amount = 6;
        if ($firstAmount > 0){
            // 创建佣金明细
            DistRewardLog::create([
                'site_id' => $siteId,
                'user_id' => $oneParent->id,
                'from_user_id' => $user->id,
                'rel_id' => $order->id,
                'rel_model' => 'order',
                'reward_type' => 1,
                'note' => '一级返佣',
                'amount' => $firstAmount,
                'rate' => $config['one_reward_rate'],
                'price' => $amount,
                'status' => 0,
            ]);
            $oneParent->save();
            // 增加用户的佣金总金额
            User::where('id', $oneParent->id)->inc('total_reward', $firstAmount)->update();

            // 二级返佣
            $twoParent = User::with('storeManager')->find($oneParent->parent_id);
            if(!$twoParent){    // 二级不存在，不返佣
                return;
            }
            if ($config['is_on_store_manager']==1 && !$twoParent->storeManager){ // 开启了店长功能，但上级不是店长，不返利
                return;
            }
            if ($config['two_reward_rate']>0){
                $secondAmount = round($amount * ($config['two_reward_rate']/100), 2);
//                $amount = 1;
                if($secondAmount>0){
                    // 创建佣金明细
                    DistRewardLog::create([
                        'site_id' => $siteId,
                        'user_id' => $twoParent->id,
                        'from_user_id' => $user->id,
                        'rel_id' => $order->id,
                        'rel_model' => 'order',
                        'reward_type' => 2,
                        'note' => '二级返佣',
                        'amount' => $secondAmount,
                        'rate' => $config['two_reward_rate'],
                        'price' => $amount,
                        'status' => 0,
                    ]);
                    $twoParent->save();
                    // 增加用户的佣金总金额
                    User::where('id', $twoParent->id)->inc('total_reward', $secondAmount)->update();
                }
            }
        }
    }
}
